﻿using System.Collections.Generic;
using UnityEngine;

namespace Framework
{
    public static class StaticBlockChunkRender
    {
        public class MeshCreatorContex
        {
            public List<Vector3> verts = new List<Vector3>();
            public List<Vector2> uvs = new List<Vector2>();
            public List<int> indices = new List<int>();
            public StaticBlockRenderConfig config;

            public void Clear()
            {
                verts.Clear(); uvs.Clear(); indices.Clear();
            }
        }
        static MeshCreatorContex contex = new MeshCreatorContex();
        public static void SetRenderConfig(StaticBlockRenderConfig cfg)
        {
            contex.config = cfg;
        }

        public static GameObject RenderStaticBlockInChunk(Chunk chunk)
        {
            GameObject chunkGo = new GameObject("StaticBlock", typeof(MeshFilter), typeof(MeshRenderer));
            chunkGo.GetComponent<MeshFilter>().mesh = GenerateMeshForStaticBlockInChunk(chunk);
            chunkGo.GetComponent<MeshRenderer>().material = contex.config.material;
            return chunkGo;
        }

        public static Mesh GenerateMeshForStaticBlockInChunk(Chunk chunk)
        {
            contex.Clear();
            for (int x = 0; x < Chunk.size.x; x++)
            {
                for (int y = 0; y < Chunk.size.y; y++)
                {
                    for (int z = 0; z < Chunk.size.z; z++)
                    {
                        Vector3Int current = new Vector3Int(x, y, z);
                        BlockType type = chunk.At(current);
                        var proto = BlockProtoDict.GetProto(type);

                        if (proto.render is StaticBlockRender)
                        {
                            (proto.render as StaticBlockRender).RenderBlock(current, chunk, contex);
                        }
                    }
                }
            }
            Mesh mesh = new Mesh();
            mesh.vertices = contex.verts.ToArray();
            mesh.uv = contex.uvs.ToArray();
            mesh.SetIndices(contex.indices, MeshTopology.Quads, 0);
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();
            contex.Clear();
            return mesh;
        }
    }
}